﻿#ifndef HTTPSERVER_H
#define HTTPSERVER_H

#include "tcpserver.h"
#include "httpcontext.h"
#include "httprequest.h"
#include "httpresponse.h"
#include <vector>
#include <string>
#include <functional>

class HttpServer
{
private:
    TcpServer m_server;
    using Handler = std::function<void(const HttpRequest &, HttpResponse *)>;
    using Handlers = std::vector<std::pair<std::regex, Handler>>;
    Handlers m_getRoute;
    Handlers m_postRoute;
    Handlers m_putRoute;
    Handlers m_deleteRoute;
    std::string m_basedic;

private:
    // 写入响应
    void writeResponse(const ConnectionPtr &conn, const HttpRequest &req, HttpResponse &rsp);
    // 是否是静态资源请求
    bool isFileHandle(HttpRequest &req, HttpResponse *rsp);
    // 静态资源请求处理
    void fileHandle(const HttpRequest &req, HttpResponse *rsp);
    // 功能请求处理
    void funcHandle(HttpRequest &req, HttpResponse *rsp, Handlers &handlers);
    // 错误请求处理
    void notFountHandle(const HttpRequest &req, HttpResponse *rsp);
    void errorHandle(const HttpRequest &req, HttpResponse *rsp);
    // 路由
    void route(HttpRequest &req, HttpResponse *rsp);
    // 设置协议上下文 --> TcpServer::SetContext
    void onConnected(const ConnectionPtr &conn);
    // 处理缓冲区和解析请求
    void onMessage(const ConnectionPtr &conn, Buffer *buf);
public:
    HttpServer(int port, int timeout = 30, const std::string &ip = defaultip);
    void start();
    //设置相对根目录
    void setBaseDic(const std::string& path);
    // 设置线程池数量
    void setThreadCount(int n);
    // 请求
    void get(const std::string &pattern, const Handler &handler);
    void post(const std::string &pattern, const Handler &handler);
    void put(const std::string &pattern, const Handler &handler);
    void del(const std::string &pattern, Handler &handler);
};

#endif